// pages/kitchen/kitchen.js
const kitchenService = require('../../services/kitchenService')

const app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    showModal: false,
    kitchen: null,
    dishes: [],
    loading: true,
    showDeleteModal: false,
    dishToDelete: null,
    showShareModal: false,  // 添加分享弹窗状态
    // 标签相关数据
    currentTag: 'all',
    tagList: [],
    tagStats: {},
    filteredDishes: [],
    theme: '',  // 添加主题数据
    showTopicModal: false,
    selectedTopicTags: [],
    customTopicInput: '', // 添加自定义专题输入
    topicTags: [
      '健康专题',
      '绿色专题',
      '创意专题',
      '节日专题',
      '新手专题'
    ],
    customTopics: [], // 用户自定义的专题列表
    topicGroups: [
      {
        groupName: '菜系',
        tags: ['川菜', '粤菜', '苏菜', '浙菜', '湘菜', '鲁菜', '徽菜', '闽菜']
      },
      {
        groupName: '场景',
        tags: ['家常菜', '下午茶', '早餐', '午餐', '晚餐', '夜宵', '野餐', '聚会']
      },
      {
        groupName: '特色',
        tags: ['创意菜', '养生', '素食', '低卡', '快手菜', '下酒菜', '下饭菜', '汤品']
      },
      {
        groupName: '烹饪方式',
        tags: ['煎炸', '烘焙', '炖煮', '蒸制', '凉拌', '烧烤', '煲汤']
      }
    ]
  },

  /**
   * 显示添加菜品选项模态框
   */
  showAddOptions() {
    this.setData({
      showModal: true
    });
  },

  /**
   * 隐藏添加菜品选项模态框
   */
  hideAddOptions() {
    this.setData({
      showModal: false
    });
  },

  /**
   * 导入菜品
   */
  importDish() {
    wx.showToast({
      title: '导入功能开发中',
      icon: 'none'
    });
    this.hideAddOptions();
  },

  /**
   * 加载默认厨房数据
   */
  async loadDefaultKitchenData() {
    this.setData({ loading: true });
    
    try {
      // 获取默认厨房
      const defaultKitchen = await kitchenService.getDefaultKitchen();
      
      if (defaultKitchen) {
        // 获取厨房的菜品
        const dishes = await kitchenService.getDishesForKitchen(defaultKitchen._id);
        
        this.setData({
          kitchen: defaultKitchen,
          dishes: dishes,
          loading: false
        });
        
        // 处理标签统计
        this.processTagsData(dishes);
      } else {
        this.setData({ loading: false });
        wx.showToast({
          title: '未找到厨房数据',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('加载厨房数据失败', error);
      this.setData({ loading: false });
      wx.showToast({
        title: '加载数据失败',
        icon: 'none'
      });
    }
  },

  /**
   * 跳转到厨房列表
   */
  navigateToKitchenList() {
    wx.navigateTo({
      url: '/pages/kitchen-list/kitchen-list'
    });
  },

  /**
   * 编辑厨房信息
   */
  editKitchen() {
    if (this.data.kitchen) {
      wx.navigateTo({
        url: `/pages/kitchen-edit/kitchen-edit?id=${this.data.kitchen._id}&mode=edit`
      });
    }
  },

  /**
   * 添加菜品
   */
  addDish() {
    if (this.data.kitchen) {
      console.log('添加菜品到厨房:', this.data.kitchen._id);
      wx.navigateTo({
        url: `/pages/dish-edit/dish-edit?kitchenId=${this.data.kitchen._id}&mode=create`,
        events: {
          // 监听菜品更新事件
          dishUpdated: (data) => {
            console.log('新菜品已添加，刷新数据:', data);
            // 重新加载厨房数据
            this.loadKitchenData(this.data.kitchen._id);
          }
        }
      });
      this.hideAddOptions();
    } else {
      wx.showToast({
        title: '请先选择厨房',
        icon: 'none'
      });
    }
  },

  /**
   * 编辑菜品
   */
  editDish(e) {
    const dishId = e.currentTarget.dataset.id;
    if (this.data.kitchen) {
      console.log('编辑菜品:', dishId);
      wx.navigateTo({
        url: `/pages/dish-edit/dish-edit?kitchenId=${this.data.kitchen._id}&dishId=${dishId}&mode=edit`,
        events: {
          // 监听菜品更新事件
          dishUpdated: (data) => {
            console.log('菜品已更新，刷新数据:', data);
            // 重新加载厨房数据
            this.loadKitchenData(this.data.kitchen._id);
          }
        }
      });
    }
  },

  /**
   * 导航到菜品详情
   */
  navigateToDishDetail(e) {
    const dishId = e.currentTarget.dataset.id;
    if (this.data.kitchen) {
      console.log('厨房页查看菜品详情:', dishId);
      wx.navigateTo({
        url: `/pages/dish-detail/dish-detail?kitchenId=${this.data.kitchen._id}&dishId=${dishId}`,
        events: {
          // 监听菜品更新事件（如果在详情页面有编辑功能）
          dishUpdated: (data) => {
            console.log('菜品从详情页更新，刷新数据:', data);
            // 重新加载厨房数据
            this.loadKitchenData(this.data.kitchen._id);
          }
        }
      });
    }
  },

  /**
   * 处理标签数据，统计每个标签的菜品数量并排序
   */
  processTagsData(dishes) {
    // 如果没有菜品，设置空数据并返回
    if (!dishes || dishes.length === 0) {
      this.setData({
        tagList: [],
        tagStats: {},
        filteredDishes: []
      });
      return;
    }
    
    // 计算每个标签的菜品数量
    const tagStats = {};
    let untaggedCount = 0;
    
    dishes.forEach(dish => {
      // 确保tags是数组
      const tags = dish.tags || [];
      
      if (tags.length === 0) {
        // 计算未分类菜品数量
        untaggedCount++;
      } else {
        // 统计每个标签的出现次数
        tags.forEach(tag => {
          if (tagStats[tag]) {
            tagStats[tag]++;
          } else {
            tagStats[tag] = 1;
          }
        });
      }
    });
    
    // 记录未分类的菜品数量
    tagStats['未分类'] = untaggedCount;
    
    // 将标签转换为数组并按菜品数量排序
    const tagList = Object.keys(tagStats)
      .filter(tag => tag !== '未分类') // 排除未分类标签，因为它会单独显示
      .map(tag => ({ tag, count: tagStats[tag] }))
      .sort((a, b) => b.count - a.count); // 按数量降序排序
    
    // 设置相关数据
    this.setData({
      tagList,
      tagStats,
      filteredDishes: this.filterDishesByTag(dishes, this.data.currentTag)
    });
  },
  
  /**
   * 根据标签筛选菜品
   */
  filterDishesByTag(dishes, tag) {
    if (tag === 'all') {
      return dishes;
    } else if (tag === '未分类') {
      return dishes.filter(dish => !dish.tags || dish.tags.length === 0);
    } else {
      return dishes.filter(dish => dish.tags && dish.tags.includes(tag));
    }
  },
  
  /**
   * 标签选择处理
   */
  selectTag(e) {
    const tag = e.currentTarget.dataset.tag;
    
    this.setData({
      currentTag: tag,
      filteredDishes: this.filterDishesByTag(this.data.dishes, tag)
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 获取当前主题
    const theme = wx.getStorageSync('theme') || 'theme-green';
    this.setData({ theme });
    
    this.setData({ loading: true });
    
    // 检查登录状态
    if (!app.checkLoginStatus()) {
      wx.redirectTo({
        url: '/pages/login/login'
      });
      return;
    }
    
    // 如果指定了厨房ID，则加载该厨房
    // 如果没有指定厨房ID，则获取默认厨房
    const kitchenId = options.id;
    
    console.log('kitchen.js onLoad - 页面参数:', options);
    
    if (kitchenId) {
      console.log('加载指定厨房:', kitchenId);
      this.loadKitchenData(kitchenId);
    } else {
      console.log('加载默认厨房');
      this.loadDefaultKitchenData();
    }

    // 加载用户自定义专题
    this.loadCustomTopics();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 检查主题是否有变化
    const theme = wx.getStorageSync('theme');
    if (theme !== this.data.theme) {
      this.setData({ theme });
    }
    
    // 检查登录状态
    if (!app.checkLoginStatus()) {
      wx.redirectTo({
        url: '/pages/login/login'
      });
      return;
    }
    
    // 获取页面栈，判断是否从厨房详情页返回
    const pages = getCurrentPages();
    const prevPage = pages.length > 1 ? pages[pages.length - 2] : null;
    
    // 如果是从厨房详情页返回，重新加载默认厨房数据
    if (prevPage && prevPage.route === 'pages/kitchen-detail/kitchen-detail') {
      // 重新加载默认厨房
      this.loadDefaultKitchenData();
    } else if (this.data.kitchen) {
      // 否则，如果已有厨房数据，只刷新当前厨房
      this.loadKitchenData(this.data.kitchen._id);
    }

    // 检查是否有选中的厨房ID
    if (app.globalData && app.globalData.selectedKitchenId) {
      const kitchenId = app.globalData.selectedKitchenId;
      // 清除选中的厨房ID
      app.globalData.selectedKitchenId = null;
      // 加载对应的厨房数据
      this.loadKitchenData(kitchenId);
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.loadDefaultKitchenData().then(() => {
      wx.stopPullDownRefresh();
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    
  },

  /**
   * 显示分享选项
   */
  shareKitchen() {
    this.setData({
      showShareModal: true
    });
  },

  /**
   * 隐藏分享选项
   */
  hideShareOptions() {
    this.setData({
      showShareModal: false
    });
  },

  /**
   * 分享到发现页
   */
  shareToDiscovery() {
    const { kitchen } = this.data;
    if (!kitchen) return;
    
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo || !userInfo._id) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      this.hideShareOptions();
      return;
    }

    const db = wx.cloud.database();
    const _ = db.command;
    
    db.collection('Share').where({
      userId: userInfo._id,
      dishId: _.exists(false),
      kitchenId: kitchen._id
    }).count().then(res => {
      if (res.total > 0) {
        wx.showToast({
          title: '您已分享过此厨房',
          icon: 'none'
        });
        this.hideShareOptions();
        return;
      }

      db.collection('Share').add({
        data: {
          userId: userInfo._id,
          userName: userInfo.nickname,
          userAvatar: userInfo.avatarUrl,
          kitchenId: kitchen._id,
          shareTime: new Date(),
          kitchenName: kitchen.name,
          kitchenImage: kitchen.image,
          kitchenDescription: kitchen.description,
          dishCount: kitchen.dishCount || 0,
        }
      }).then(() => {
        wx.showToast({
          title: '分享成功',
          icon: 'success'
        });
        this.hideShareOptions();
      }).catch(err => {
        console.error('分享厨房失败:', err);
        wx.showToast({
          title: '分享失败',
          icon: 'error'
        });
        this.hideShareOptions();
      });
    }).catch(err => {
      console.error('检查分享记录失败:', err);
      wx.showToast({
        title: '操作失败，请重试',
        icon: 'none'
      });
      this.hideShareOptions();
    });
  },

  /**
   * 用户点击右上角分享（或点击分享给微信好友）
   */
  onShareAppMessage() {
    const kitchen = this.data.kitchen || {};
    return {
      title: `${kitchen.name || '我的厨房'}`,
      path: `/pages/kitchen/kitchen?id=${kitchen._id}`,
      imageUrl: kitchen.image || '/imgs/chef-hat.svg'
    };
  },

  loadDefaultKitchen: function() {
    console.log('开始加载默认厨房');
    
    // 强制清除默认厨房ID缓存，确保重新获取最新的默认厨房数据
    try {
      wx.removeStorageSync('defaultKitchen');
      console.log('已清除本地默认厨房缓存');
    } catch (e) {
      console.error('清除缓存失败', e);
    }
    
    kitchenService.getDefaultKitchen().then(defaultKitchen => {
      console.log('获取到默认厨房:', defaultKitchen);
      if (defaultKitchen) {
        this.loadKitchenData(defaultKitchen._id);
      } else {
        // 没有默认厨房，检查是否有任何厨房
        console.log('未找到默认厨房，尝试获取所有厨房');
        kitchenService.getAllKitchens().then(kitchens => {
          if (kitchens && kitchens.length > 0) {
            // 加载第一个厨房
            console.log('加载第一个厨房:', kitchens[0]);
            this.loadKitchenData(kitchens[0]._id);
          } else {
            // 没有任何厨房
            console.log('没有发现任何厨房');
            this.setData({ loading: false });
          }
        }).catch(err => {
          console.error('获取厨房列表失败', err);
          this.setData({ loading: false });
        });
      }
    }).catch(err => {
      console.error('获取默认厨房失败', err);
      this.setData({ loading: false });
    });
  },

  loadKitchenData: function(kitchenId) {
    if (!kitchenId) return;
    
    // 显示加载提示
    wx.showLoading({
      title: '加载中...'
    });

    this.setData({ loading: true });
    
    Promise.all([
      kitchenService.getKitchenById(kitchenId),
      kitchenService.getDishesForKitchen(kitchenId)
    ]).then(([kitchen, dishes]) => {
      this.setData({
        kitchen: kitchen,
        dishes: dishes,
        loading: false
      });
      
      // 处理标签统计
      this.processTagsData(dishes);
      wx.hideLoading();
    }).catch(err => {
      console.error('加载厨房数据失败', err);
      wx.hideLoading();
      wx.showToast({
        title: '加载数据失败',
        icon: 'none'
      });
      this.setData({ loading: false });
    });
  },

  navigateToEditKitchen: function() {
    wx.navigateTo({
      url: `/pages/kitchen-edit/kitchen-edit?id=${this.data.kitchen._id}`
    });
  },

  navigateToKitchenList: function() {
    wx.navigateTo({
      url: '/pages/kitchen-list/kitchen-list'
    });
  },

  navigateToAddDish: function() {
    wx.navigateTo({
      url: `/pages/dish-edit/dish-edit?kitchenId=${this.data.kitchen._id}`
    });
  },

  navigateToEditDish: function(e) {
    const dishId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/dish-edit/dish-edit?kitchenId=${this.data.kitchen._id}&dishId=${dishId}&mode=edit`
    });
  },
  
  showDeleteDishModal: function(e) {
    const dishId = e.currentTarget.dataset.id;
    const dish = this.data.dishes.find(d => d._id === dishId);
    
    this.setData({
      showDeleteModal: true,
      dishToDelete: dish
    });
  },
  
  hideDeleteModal: function() {
    this.setData({
      showDeleteModal: false,
      dishToDelete: null
    });
  },
  
  confirmDeleteDish: function() {
    const dishId = this.data.dishToDelete._id;
    const kitchenId = this.data.kitchen._id;
    
    kitchenService.deleteDish(kitchenId, dishId)
      .then(() => {
        wx.showToast({
          title: '删除成功',
          icon: 'success'
        });
        
        // 更新列表
        const updatedDishes = this.data.dishes.filter(dish => dish._id !== dishId);
        this.setData({
          dishes: updatedDishes,
          showDeleteModal: false,
          dishToDelete: null
        });
        
        // 重新处理标签数据
        this.processTagsData(updatedDishes);
      })
      .catch(err => {
        console.error('删除菜品失败', err);
        wx.showToast({
          title: '删除失败',
          icon: 'none'
        });
      });
  },

  /**
   * 显示专题标签选择弹窗
   */
  showTopicSelect() {
    this.setData({
      showTopicModal: true,
      showShareModal: false
    });
  },

  /**
   * 隐藏专题标签选择弹窗
   */
  hideTopicSelect() {
    this.setData({
      showTopicModal: false
    });
  },

  /**
   * 切换专题标签选择状态
   */
  toggleTopicTag(e) {
    const tag = e.currentTarget.dataset.tag;
    const selectedTopicTags = [...this.data.selectedTopicTags];
    
    if (selectedTopicTags.includes(tag)) {
      // 如果点击已选中的标签，则取消选择
      this.setData({ selectedTopicTags: [] });
    } else {
      // 选择新标签时，替换原有选择
      this.setData({ selectedTopicTags: [tag] });
    }
  },

  /**
   * 移除已选标签
   */
  removeTopicTag(e) {
    this.setData({ 
      selectedTopicTags: [] 
    });
  },

  /**
   * 确认分享到专题
   */
  async confirmShareToTopic() {
    try {
      wx.showLoading({
        title: '正在分享',
        mask: true
      });

      const result = await kitchenService.shareKitchenToTopic({
        kitchenId: this.data.kitchen._id,
        tags: this.data.selectedTopicTags.length > 0 ? this.data.selectedTopicTags : undefined
      });

      wx.hideLoading();
      
      if (result.success) {
        wx.showToast({
          title: '分享成功',
          icon: 'success'
        });
        this.hideTopicSelect();
        // 重置选中的标签
        this.setData({ selectedTopicTags: [] });
      } else {
        throw new Error(result.message || '分享失败');
      }
    } catch (error) {
      console.error('分享到专题失败:', error);
      wx.hideLoading();
      wx.showToast({
        title: error.message || '分享失败',
        icon: 'none'
      });
    }
  },

  /**
   * 加载用户自定义专题
   */
  async loadCustomTopics() {
    try {
      const customTopics = wx.getStorageSync('customTopics') || [];
      this.setData({ customTopics });
    } catch (error) {
      console.error('加载自定义专题失败:', error);
    }
  },

  /**
   * 添加自定义专题
   */
  addCustomTopic() {
    const { customTopicInput, customTopics, topicTags } = this.data;
    
    if (!customTopicInput.trim()) {
      wx.showToast({
        title: '请输入专题名称',
        icon: 'none'
      });
      return;
    }

    // 检查是否已存在（包括预设专题和自定义专题）
    if (topicTags.includes(customTopicInput) || customTopics.includes(customTopicInput)) {
      wx.showToast({
        title: '该专题已存在',
        icon: 'none'
      });
      return;
    }

    const newCustomTopics = [...customTopics, customTopicInput];
    
    // 保存到本地存储
    wx.setStorageSync('customTopics', newCustomTopics);
    
    this.setData({
      customTopics: newCustomTopics,
      customTopicInput: '' // 清空输入
    });
  },

  /**
   * 删除自定义专题
   */
  deleteCustomTopic(e) {
    const topic = e.currentTarget.dataset.topic;
    const customTopics = this.data.customTopics.filter(t => t !== topic);
    
    // 如果要删除的专题在已选中的标签中，也要移除
    const selectedTopicTags = this.data.selectedTopicTags.filter(t => t !== topic);
    
    // 更新本地存储
    wx.setStorageSync('customTopics', customTopics);
    
    this.setData({ customTopics, selectedTopicTags });
  },

  /**
   * 处理自定义专题输入
   */
  onCustomTopicInput(e) {
    this.setData({
      customTopicInput: e.detail.value
    });
  },
}) 